package com.fengba.nanzhi.myinfo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.login.Login;
import com.fengba.nanzhi.notice.Notice;
import com.fengba.nanzhi.notice.NoticeAdapter;
import com.fengba.nanzhi.tabbar04.wz.CardActivity;
import com.fengba.nanzhi.tabbar04.wz.IdnumberActivity;
import com.fengba.nanzhi.tabbar04.wz.ThirdpartyActivity;
import com.fengba.nanzhi.utils.FX_SignInUtil;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * Created by SpakeBrony on 2018/4/9.
 */

public class MyInfo extends Activity {


    protected static final int CAMERA_REQUEST_CODE = 0;
    protected static final int ALBUM_REQUEST_CODE = 1;
    private static final int CROP_REQUEST_CODE = 2;
    final static int CAMERA_RESULT = 0;//声明一个常量，代表结果码

    private LinearLayout LL03;

    public MyInfo() {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fx_myinfo);
        LL03 = (LinearLayout) findViewById(R.id.LL03);
        /**
         * 拍照
         */
        TextView MIpz = (TextView) findViewById(R.id.MIpz);
        MIpz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LL03.setVisibility(View.INVISIBLE);
                /**这里有2种获取相册的方式*/
                //Intent intent = new Intent(Intent.ACTION_GET_CONTENT);//图库
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//实例化Intent对象,使用MediaStore的ACTION_IMAGE_CAPTURE常量调用系统相机
                //intent.setType("image/*");
                //Intent intent = new Intent(Intent.ACTION_PICK, null);
                //intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                //startActivityForResult(intent, ALBUM_REQUEST_CODE);
                startActivityForResult(intent, CAMERA_RESULT);//开启相机，传入上面的Intent对象
            }
        });


        /**
         * 图库
         */
        TextView MYxc = (TextView) findViewById(R.id.MYxc);
        MYxc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LL03.setVisibility(View.INVISIBLE);
                /**这里有2种获取相册的方式*/
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);//图库
                //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//实例化Intent对象,使用MediaStore的ACTION_IMAGE_CAPTURE常量调用系统相机
                intent.setType("image/*");
                //Intent intent = new Intent(Intent.ACTION_PICK, null);
                //intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, ALBUM_REQUEST_CODE);
                //startActivityForResult(intent, CAMERA_RESULT);//开启相机，传入上面的Intent对象
            }
        });

        /**
         * 取消
         */
        TextView MYend = (TextView) findViewById(R.id.MYend);
        MYend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        LL03.setVisibility(View.INVISIBLE);
                    }
                }, 300);
            }
        });

        /**
         * 头像
         */
        Button Mibtn01 = (Button) findViewById(R.id.Mibtn01);
        Mibtn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        LL03.setVisibility(View.VISIBLE);
                    }
                }, 300);

            }
        });

        /**
         * 返回
         */
        ImageButton MIreturn = (ImageButton) findViewById(R.id.MIreturn);
        MIreturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                //getActivity().overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            }
        });
        /**
         * 微信号
         */
        Button Mibtn05 = (Button) findViewById(R.id.Mibtn05);
        Mibtn05.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyInfo.this, WxAccount.class);
                startActivity(intent);
            }
        });
        /**
         * 微信二维码
         */
        Button Mibtn06 = (Button) findViewById(R.id.Mibtn06);
        Mibtn06.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyInfo.this, WxImg.class);
                startActivity(intent);
            }
        });
        /**
         * 我的银行卡
         */
        Button Mibtn03 = (Button) findViewById(R.id.Mibtn03);
        Mibtn03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyInfo.this, CardActivity.class);
                startActivity(intent);
            }
        });
        /**
         * 实名认证
         */
        Button Mibtn02 = (Button) findViewById(R.id.Mibtn02);
        Mibtn02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyInfo.this, IdnumberActivity.class);
                startActivity(intent);
            }
        });
        /**
         * 第三方服务
         */
        Button Mibtn04 = (Button) findViewById(R.id.Mibtn04);
        Mibtn04.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyInfo.this, ThirdpartyActivity.class);
                startActivity(intent);
            }
        });

        /**
         * 隐私开关
         */
        Switch mSwitch = (Switch) findViewById(R.id.switch1);
        String privacy = null;
        try {
            Object user_info = Preferences.getParam(MyInfo.this, "user_info", "");
            JSONObject myJson = null;
            myJson = new JSONObject(user_info.toString());
            privacy = myJson.get("privacy").toString();
            if (privacy.equals("1")) {
                mSwitch.setChecked(true);
            } else {
                mSwitch.setChecked(false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // 添加监听
        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String sc = null;
                if (isChecked) {
                    sc = "0";
                    //开启"
                    inits(sc);
                } else {
                    sc = "1";
                    //关闭"
                    inits(sc);
                }
            }
        });

    }//都在这里打


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_CANCELED)
                return;
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                Bitmap bitmap = bundle.getParcelable("data");
                Uri uri = saveBitmap(bitmap);
                startImageZoom(uri);
            }
        } else if (requestCode == ALBUM_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_CANCELED)
                return;
            Uri uri = data.getData();
            Uri fileUri = converUri(uri);
            startImageZoom(fileUri);
        } else if (requestCode == CROP_REQUEST_CODE) {
            Bundle bundle = data.getExtras();
            Bitmap bitmap = bundle.getParcelable("data");
            //将突破上传到控件上，暂时不需要
            //WXimg01.setImageBitmap(bitmap);
            sendImage(bitmap);
        }
    }

    /**
     * 裁剪
     *
     * @param uri
     */
    private void startImageZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    /**
     * 将Content的Uri转成file的Uri
     *
     * @param uri
     * @return
     */
    private Uri converUri(Uri uri) {
        InputStream in = null;
        try {
            in = getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将Bitmap转成file的Uri
     *
     * @param bitmap
     * @return
     */
    private Uri saveBitmap(Bitmap bitmap) {
        File file = new File(Environment.getExternalStorageDirectory() + "/aaa");
        if (!file.exists())
            file.mkdirs();
        File imgFile = new File(file.getAbsolutePath() + "/1.jpeg");
        if (imgFile.exists())
            imgFile.delete();
        try {
            FileOutputStream outputStream = new FileOutputStream(imgFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);


            outputStream.flush();
            outputStream.close();
            Uri uri = Uri.fromFile(imgFile);
            return uri;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 上传图片到服务器
     *
     * @param bitmap
     */
    private void sendImage(Bitmap bitmap) {
        File file = new File(Environment.getExternalStorageDirectory() + "/aaa");
        if (!file.exists())
            file.mkdirs();
        File imgFile = new File(file.getAbsolutePath() + "/headimg1.jpeg");
        if (imgFile.exists())
            imgFile.delete();
        try {
            FileOutputStream outputStream = new FileOutputStream(imgFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            init(imgFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void init(File file) {
        String id = null;
        try {
            Object user_info = Preferences.getParam(MyInfo.this, "user_info", "");
            JSONObject myJson = null;
            myJson = new JSONObject(user_info.toString());
            id = myJson.get("id").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (FX_SignInUtil.switchAccount(MyInfo.this)) {
            startActivity(new Intent(MyInfo.this, Login.class));
        } else {
            OKManager.getInstance().type2020(id, file);
            Toast.makeText(MyInfo.this, "上传成功", Toast.LENGTH_SHORT).show();
        }
    }


    public void inits(String sw) {
        String id = null;
        try {
            Object user_info = Preferences.getParam(MyInfo.this, "user_info", "");
            JSONObject myJson = null;
            myJson = new JSONObject(user_info.toString());
            id = myJson.get("id").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (FX_SignInUtil.switchAccount(MyInfo.this)) {
            startActivity(new Intent(MyInfo.this, Login.class));
        } else {
            OKManager.getInstance().type2021(id, sw, new OKManager.func4() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        Toast.makeText(MyInfo.this, jsonObject.get("message").toString(), Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String string) {
                    Toast.makeText(MyInfo.this, "网络错误", Toast.LENGTH_SHORT).show();
                }
            });
        }


    }
}